What is the fastest (possibly unsafe) way to read a byte[]?

Posted by Aidiakapi on Stack Overflow See other posts from Stack Overflow or by Aidiakapi
Published on 2011-03-04T15:12:32Z Indexed on 2011/03/04 15:24 UTC
Read the original article Hit count: 204

Filed under:
|
|
|

I'm working on a server project in C#, and after a TCP message is received, it is parsed, and stored in a byte[] of exact size. (Not a buffer of fixed length, but a byte[] of an absolute length in which all data is stored.)

Now for reading this byte[] I'll be creating some wrapper functions (also for compatibility), these are the signatures of all functions I need:

public byte ReadByte();
public sbyte ReadSByte();
public short ReadShort();
public ushort ReadUShort();
public int ReadInt();
public uint ReadUInt();
public float ReadFloat();
public double ReadDouble();
public string ReadChars(int length);
public string ReadString();

The string is a \0 terminated string, and is probably encoded in ASCII or UTF-8, but I cannot tell that for sure, since I'm not writing the client.

The data exists of:

byte[] _data;
int _offset;

Now I can write all those functions manually, like this:

public byte ReadByte()
{
    return _data[_offset++];
}

public sbyte ReadSByte()
{
    byte r = _data[_offset++];
    if (r >= 128) return (sbyte)(r - 256);
    else return (sbyte)r;
}

public short ReadShort()
{
    byte b1 = _data[_offset++];
    byte b2 = _data[_offset++];
    if (b1 >= 128) return (short)(b1 * 256 + b2 - 65536);
    else return (short)(b1 * 256 + b2);
}

public short ReadUShort()
{
    byte b1 = _data[_offset++];
    return (short)(b1 * 256 + _data[_offset++]);
}

But I wonder if there's a faster way, not excluding the use of unsafe code, since this seems a little bit too much work for simple processing.

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading